package com.student.web.student;

import com.student.pojo.Student;
import com.student.service.student.StudentService;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * get /post 参数 student各字段
 * 返回 ok err
 * @author lin945
 * @date 2020/5/6 21:29
 */
@WebServlet("/addStudent")
public class addStudent extends HttpServlet {
    private StudentService studentService=new StudentService();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setHeader("Content-type","text/html;charset=UTF-8");
        HttpSession session = req.getSession();
        if (session.getAttribute("username") == null) {
            resp.sendRedirect(req.getContextPath() + "/login");
            return;
        }
        Student student = new Student();
        Map<String, String[]> parameterMap = req.getParameterMap();
        try {
            BeanUtils.populate(student,parameterMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            resp.getWriter().write("err"+e);
        } catch (InvocationTargetException e) {
            e.printStackTrace();
            resp.getWriter().write("err"+e);
        }
if(studentService.saveStudent(student)){
    resp.getWriter().write("ok");
}else{
    resp.getWriter().write("err");
}

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
